from app import db
from datetime import datetime

class Project(db.Model):
    __tablename__ = 'projects'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), nullable=False)
    project_code = db.Column(db.String(64), unique=True, nullable=False)
    project_type = db.Column(db.String(64), nullable=False)  # 工业测控、环境监测等
    scale = db.Column(db.JSON)  # 存储监测点数、控制回路数量等
    
    # 项目文档
    documents = db.relationship('ProjectDocument', backref='project', lazy=True)
    
    # 测控目标与要求
    control_targets = db.relationship('ControlTarget', backref='project', lazy=True)
    
    # 环境信息
    environment = db.relationship('Environment', backref=db.backref('project', lazy=True),
                                uselist=False, lazy=True,
                                cascade='all, delete-orphan')
    
    # 资源信息
    resources = db.relationship('Resource', backref=db.backref('project', lazy=True),
                              uselist=False, lazy=True,
                              cascade='all, delete-orphan')
    
    # 创建和更新时间
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 创建者和当前状态
    creator_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    status = db.Column(db.String(20), default='draft')  # draft, submitted, approved, rejected

    def __init__(self, name, project_code, project_type, creator_id, scale=None, status='draft'):
        self.name = name
        self.project_code = project_code
        self.project_type = project_type
        self.creator_id = creator_id
        self.scale = scale or {}
        self.status = status

    @staticmethod
    def validate_project_code(project_code):
        """验证项目编号格式"""
        if not project_code or len(project_code) < 4:
            return False
        return True

    def validate_scale(self):
        """验证项目规模数据"""
        if not isinstance(self.scale, dict):
            return False
        
        monitoring_points = self.scale.get('monitoring_points')
        control_loops = self.scale.get('control_loops')
        
        if not (isinstance(monitoring_points, int) and isinstance(control_loops, int)):
            return False
            
        if monitoring_points <= 0 or control_loops <= 0:
            return False
            
        return True

    @property
    def status_text(self):
        """获取状态的中文描述"""
        status_map = {
            'draft': '草稿',
            'pending': '待审核',
            'approved': '已批准',
            'rejected': '已拒绝'
        }
        return status_map.get(self.status, '未知状态')

class ProjectDocument(db.Model):
    __tablename__ = 'project_documents'
    
    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'))
    name = db.Column(db.String(128))
    file_path = db.Column(db.String(256))
    doc_type = db.Column(db.String(64))  # 需求文档、技术规格书等
    uploaded_at = db.Column(db.DateTime, default=datetime.utcnow)

class ControlTarget(db.Model):
    __tablename__ = 'control_targets'
    
    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'))
    target_type = db.Column(db.String(64))  # 温度、压力、流量等
    parameter = db.Column(db.String(64))  # 阀门开度、电机转速等
    requirements = db.Column(db.JSON)  # 精度要求、响应时间要求等

# Environment and Resource models are now in their own files 